package com.atguigu.daijia.common.login;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GlobalException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect // 声明这是一个切面
public class LoginCheckAspect {

    @Resource
    private RedisTemplate redisTemplate;

    @Around("@annotation(loginCheck) && execution(* com.atguigu.daijia.*.controller.*.*(..))")
    public Object login(ProceedingJoinPoint joinPoint, LoginCheck loginCheck) throws Throwable {
        // 获取请求对象
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) attributes;
        HttpServletRequest request = sra.getRequest();
        // 获取请求头中的token
        String token = request.getHeader("token");
        // 判断token是否为空
        if(!StringUtils.hasText(token)){
            throw new GlobalException(ResultCodeEnum.LOGIN_AUTH);
        }
        // 如果token不为空，则查询redis
        String customerId = (String)redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        if(StringUtils.hasText(customerId)){
            AuthContextHolder.setUserId(Long.parseLong(customerId));
        }

        return joinPoint.proceed();
    }
}
